<!-- templates/warehouse/warehouselist.html -->
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>仓库管理 - 商店进销存管理系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 从 unpkg CDN 引入 ECharts -->
    <script src="https://unpkg.com/echarts@5.4.0/dist/echarts.min.js"></script>

    <!-- 引入 Toastify CSS 和 JS -->
    <link href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.js"></script>

    <!-- Tailwind 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        success: '#00B42A',
                        warning: '#FF7D00',
                        danger: '#F53F3F',
                        info: '#86909C'
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }

            .sidebar-item {
                @apply flex items-center px-4 py-3 text-gray-600 hover:bg-gray-50 hover:text-primary transition-all duration-200;
            }

            .sidebar-item.active {
                @apply bg-primary/10 text-primary border-l-4 border-primary;
            }

            .card-shadow {
                @apply shadow-md hover:shadow-lg transition-shadow duration-300;
            }
            .echart-container {
                width: 100%;
                height: 350px; /* 初始高度，可根据需求调整 */
            }
        }
    </style>
</head>

<body class="font-inter bg-gray-50 min-h-screen flex flex-col">
<!-- 顶部导航栏 -->
<header class="bg-white shadow-sm">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
        <div class="flex items-center space-x-2">
            <i class="fa fa-cubes text-primary text-2xl"></i>
            <h1 class="text-xl font-bold text-gray-800">商店进销存管理系统</h1>
        </div>

        <div class="flex items-center space-x-6">
            <div class="relative">
                <input type="text" placeholder="搜索..."
                       class="pl-10 pr-4 py-2 rounded-full border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
            </div>

            <div class="flex items-center space-x-4">
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-bell-o text-xl"></i>
                </button>
                <button class="text-gray-600 hover:text-primary transition-colors">
                    <i class="fa fa-cog text-xl"></i>
                </button>
                <div class="flex items-center space-x-2 cursor-pointer">
                    <img src="https://picsum.photos/200/200" alt="用户头像" class="w-8 h-8 rounded-full object-cover">
                    <span class="text-gray-700">管理员</span>
                </div>
            </div>
        </div>
    </div>
</header>

<div class="flex flex-1 overflow-hidden">
    <!-- 侧边栏导航 -->
    <aside class="w-64 bg-white shadow-md h-[calc(100vh-64px)] overflow-y-auto transition-all duration-300">
        <nav class="py-4">
            <div class="px-4 mb-4">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">主菜单</h2>
            </div>

            <a href="index.html" class="sidebar-item" data-path="index.html">
                <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
                <span>仪表盘</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">基础信息</h2>
            </div>

            <a href="productlist.html" class="sidebar-item" data-path="productlist.html">
                <i class="fa fa-shopping-bag w-5 h-5 mr-3"></i>
                <span>商品管理</span>
            </a>

            <a href="categorylist.html" class="sidebar-item" data-path="categorylist.html">
                <i class="fa fa-th-large w-5 h-5 mr-3"></i>
                <span>类别管理</span>
            </a>

            <a href="supplierlist.html" class="sidebar-item" data-path="supplierlist.html">
                <i class="fa fa-truck w-5 h-5 mr-3"></i>
                <span>供应商管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">库存管理</h2>
            </div>

            <a href="warehouselist.html" class="sidebar-item active" data-path="warehouselist.html">
                <i class="fa fa-archive w-5 h-5 mr-3"></i>
                <span>仓库管理</span>
            </a>

            <a href="inventorylist.html" class="sidebar-item" data-path="inventorylist.html">
                <i class="fa fa-list-alt w-5 h-5 mr-3"></i>
                <span>库存查询</span>
            </a>

            <a href="instock.html" class="sidebar-item" data-path="instock.html">
                <i class="fa fa-sign-in w-5 h-5 mr-3"></i>
                <span>入库管理</span>
            </a>

            <a href="outstock.html" class="sidebar-item " data-path="outstock.html">
                <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
                <span>出库管理</span>
            </a>

            <a href="transfer.html" class="sidebar-item" data-path="transfer.html">
                <i class="fa fa-exchange w-5 h-5 mr-3"></i>
                <span>转仓管理</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">统计分析</h2>
            </div>

            <a href="statistics/sales.html" class="sidebar-item">
                <i class="fa fa-line-chart w-5 h-5 mr-3"></i>
                <span>销售统计</span>
            </a>

            <a href="statistics/inventory.html" class="sidebar-item">
                <i class="fa fa-pie-chart w-5 h-5 mr-3"></i>
                <span>库存分析</span>
            </a>

            <div class="px-4 mt-6 mb-2">
                <h2 class="text-xs font-semibold text-gray-400 uppercase tracking-wider">系统设置</h2>
            </div>

            <a href="salesman.html" class="sidebar-item" data-path="salesman.html">
                <i class="fa fa-user-circle w-5 h-5 mr-3"></i>
                <span>用户管理</span>
            </a>


            <a href="backup.html" class="sidebar-item" data-path="system/logs.html">
                <i class="fa fa-history w-5 h-5 mr-3"></i>
                <span>数据库备份与恢复</span>
            </a>
        </nav>
    </aside>

    <!-- 主内容区域 -->
    <main class="flex-1 overflow-y-auto bg-gray-50 p-6">
        <div class="container mx-auto">
            <!-- 页面标题 -->
            <div class="mb-6">
                <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">仓库管理</h2>
                <p class="text-gray-500 mt-1">管理商店的所有仓库信息</p>
            </div>

            <!-- 操作按钮 -->
            <div class="mb-4 flex justify-between items-center">
                <button class="bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center" id="addWarehouseBtn">
                    <i class="fa fa-plus mr-2"></i> 添加仓库
                </button>
                <div class="flex space-x-2">
                    <button class="bg-gray-100 text-gray-600 px-4 py-2 rounded-md hover:bg-gray-200" id="filterBtn">
                        <i class="fa fa-filter mr-1"></i> 筛选
                    </button>
                    <button class="bg-gray-100 text-gray-600 px-4 py-2 rounded-md hover:bg-gray-200">
                        <i class="fa fa-download mr-1"></i> 导出
                    </button>
                </div>
            </div>

            <!-- 筛选表单 -->
            <div id="filterForm" class="mb-4 bg-white rounded-lg p-4 card-shadow hidden">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">仓库名称</label>
                        <input type="text" id="filterName" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入仓库名称">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">状态</label>
                        <select id="filterStatus" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent">
                            <option value="">全部状态</option>
                            <option value="Active">活跃</option>
                            <option value="Inactive">非活跃</option>
                            <option value="UnderMaintenance">维护中</option>
                            <option value="Planned">规划中</option>
                        </select>
                    </div>
                    <div class="flex items-end space-x-2">
                        <button id="applyFilterBtn" class="flex-1 bg-primary text-white px-4 py-2 rounded-md hover:bg-primary/90 flex items-center justify-center">
                            <i class="fa fa-search mr-2"></i> 搜索
                        </button>
                        <button id="resetFilterBtn" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">
                            重置
                        </button>
                    </div>
                </div>
            </div>

            <!-- 仓库列表 -->
            <div class="bg-white rounded-xl p-6 card-shadow">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead>
                        <tr class="border-b border-gray-200">
                            <th class="py-3 text-left text-sm font-medium text-gray-500">仓库ID</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">仓库名称</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">地址</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">总容量</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">已使用</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">状态</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">负责人</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">库存预警</th>
                            <th class="py-3 text-left text-sm font-medium text-gray-500">操作</th>
                        </tr>
                        </thead>
                        <tbody id="warehouseTable">
                        <!-- 数据将通过JS动态渲染 -->
                        <tr>
                            <td colspan="9" class="py-4 text-center">
                                <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
                                <p class="mt-2 text-gray-600">加载仓库数据中...</p>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>

                <!-- 分页控件 -->
                <div class="mt-6 flex justify-between items-center">
                    <div class="text-sm text-gray-500" id="paginationInfo">共 0 条记录</div>
                    <div class="flex space-x-1" id="paginationControls">
                        <!-- 分页控件将通过JS动态渲染 -->
                    </div>
                </div>
            </div>

            <!-- 仓库数据统计图表 -->
            <div class="mt-6 grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div class="bg-white rounded-xl p-6 card-shadow">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">仓库容量使用情况</h3>
                    <div class="bg-gray-50 p-4 rounded-lg" id="capacityBarChart">
                        <!-- ECharts图表将通过JS动态渲染 -->
                        <div class="text-center py-8 text-gray-500">
                            <i class="fa fa-spinner fa-spin text-xl mb-2"></i>
                            <p>加载中...</p>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl p-6 card-shadow">
                    <h3 class="text-lg font-semibold text-gray-800 mb-4">仓库状态分布</h3>
                    <div class="bg-gray-50 p-4 rounded-lg" id="statusPieChart">
                        <!-- ECharts图表将通过JS动态渲染 -->
                        <div class="text-center py-8 text-gray-500">
                            <i class="fa fa-spinner fa-spin text-xl mb-2"></i>
                            <p>加载中...</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>
<!-- 页脚 -->
<footer class="bg-white py-4 border-t border-gray-200">
    <div class="container mx-auto px-4 text-center text-gray-500 text-sm">
        <p>© 2025 商店进销存管理系统 - 版权所有</p>
    </div>
</footer>

<!-- 仓库添加模态框 -->
<div id="warehouseModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>
<!-- 仓库编辑模态框 -->
<div id="editWarehouseModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden"></div>

<script>
    // 权限检查函数
    function hasPermission(permissionCode) {
        // 从localStorage或cookie中获取用户权限列表
        const userPermissions = JSON.parse(localStorage.getItem('userPermissions') || '[]');
        return userPermissions.includes(permissionCode);
    }

    // 根据角色隐藏/展示按钮
    const applyRolePermissions = () => {
        fetch('/user-info')
            .then(response => {
                if (!response.ok) {
                    throw new Error(`获取用户信息失败: 状态码 ${response.status}`);
                }
                return response.json(); // 解析JSON格式响应
            })
            .then(data => {
                console.log('用户信息响应:', data);

                // 检查响应结构是否正确
                if (data.code !== "200" || !data.data) {
                    throw new Error(data.message || '响应数据格式错误');
                }

                const userData = data.data;
                const authorities = userData.authorities;

                // 使用正则表达式提取角色信息（假设authorities格式为"Roles:[ROLE_USER]"）
                const roles = authorities.match(/Roles:\[(.*?)\]/);
                if (roles) {
                    const roleList = roles[1].split(","); // 注意：后端返回的是ROLE_USER，无空格，使用逗号直接分割
                    console.log('用户角色:', roleList);

                    // 存储用户权限到localStorage
                    localStorage.setItem('userPermissions', JSON.stringify(roleList));

                    if (!roleList.includes("ROLE_ADMIN")) {
                        // 隐藏管理员专属按钮
                        const addWarehouseBtn = document.getElementById('addWarehouseBtn');
                        if (addWarehouseBtn) {
                            addWarehouseBtn.style.display = 'none';
                        }

                        // 隐藏需要管理员权限的按钮
                        document.querySelectorAll('[data-permission]').forEach(button => {
                            const requiredPermission = button.getAttribute('data-permission');
                            if (!hasPermission(requiredPermission)) {
                                button.style.display = 'none';
                            }
                        });
                    }
                } else {
                    console.warn('未找到角色信息，原始数据:', authorities);
                }
            })
            .catch(error => {
                console.error('获取用户信息失败:', error);
                Toastify({
                    text: '获取用户权限失败，请重新登录',
                    duration: 3000,
                    gravity: 'top',
                    position: 'right',
                    backgroundColor: '#f44336'
                }).showToast();
            });
    };

    // 确保在商品数据加载完成后再次应用权限
    const ensurePermissionsApplied = () => {
        // 如果数据是异步加载的，可能需要在数据加载完成后再次调用
        setTimeout(() => {
            applyRolePermissions();
        }, 500); // 等待500毫秒，确保数据加载完成
    };

    // 全局变量存储当前编辑的仓库ID
    let currentEditingWarehouseId = null;
    // 全局筛选参数
    let filterParams = {
        name: '',
        status: ''
    };
    // 存储所有仓库数据
    let allWarehouses = [];
    // 全局ECharts实例
    let capacityChart = null;
    let statusChart = null;

    // 页面加载完成后初始化
    document.addEventListener('DOMContentLoaded', () => {
        initSidebarNavigation();
        setCurrentPageActive();

        // 延迟执行，确保所有资源都加载完成
        setTimeout(() => {
            loadWarehouses();
        }, 300); // 延迟300毫秒

        // 应用角色权限
        applyRolePermissions();

        // 确保数据加载完成后再次应用权限
        ensurePermissionsApplied();
        // 筛选按钮点击事件
        document.getElementById('filterBtn').addEventListener('click', () => {
            const filterForm = document.getElementById('filterForm');
            filterForm.classList.toggle('hidden');
        });

        // 应用筛选按钮点击事件
        document.getElementById('applyFilterBtn').addEventListener('click', applyFilter);

        // 重置筛选按钮点击事件
        document.getElementById('resetFilterBtn').addEventListener('click', resetFilter);

        // 绑定添加仓库按钮事件
        document.getElementById('addWarehouseBtn').addEventListener('click', showAddWarehouseForm);

        // 绑定编辑商品按钮事件
        document.addEventListener('click', (e) => {
            // 处理编辑按钮
            if (e.target.closest('.edit-btn')) {
                const button = e.target.closest('.edit-btn');
                const warehouseId = parseInt(button.getAttribute('data-id'));
                editWarehouse(warehouseId);
            }

            // 处理删除按钮
            if (e.target.closest('.delete-btn')) {
                const button = e.target.closest('.delete-btn');
                const warehouseId = parseInt(button.getAttribute('data-id'));
                deleteWarehouse(warehouseId);
            }
        });
    });

    /**
     * 应用筛选条件
     */
    const applyFilter = () => {
        // 获取筛选表单的值
        filterParams = {
            name: document.getElementById('filterName').value.trim(),
            status: document.getElementById('filterStatus').value
        };

        // 从第一页开始加载数据
        loadWarehouses(0);
    };

    /**
     * 重置筛选条件
     */
    const resetFilter = () => {
        // 重置表单
        document.getElementById('filterName').value = '';
        document.getElementById('filterStatus').value = '';

        // 重置筛选参数
        filterParams = {
            name: '',
            status: ''
        };

        // 从第一页开始加载数据
        loadWarehouses(0);
    };

    /**
     * 从后端API加载仓库数据（支持筛选）
     */
    let currentPage = 0; // 保存当前页码（后端从0开始）
    const loadWarehouses = (page = 0) => {
        const warehouseTable = document.getElementById('warehouseTable');
        const paginationInfo = document.getElementById('paginationInfo');
        const paginationControls = document.getElementById('paginationControls');
        const capacityChartContainer = document.getElementById('capacityBarChart');
        const statusChartContainer = document.getElementById('statusPieChart');

        // 显示加载中状态
        warehouseTable.innerHTML = `
        <tr>
          <td colspan="9" class="py-4 text-center">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            <p class="mt-2 text-gray-600">加载仓库数据中...</p>
          </td>
        </tr>
      `;

        if (capacityChartContainer) {
            capacityChartContainer.innerHTML = `
          <div class="text-center py-8 text-gray-500">
            <i class="fa fa-spinner fa-spin text-xl mb-2"></i>
            <p>加载中...</p>
          </div>
        `;
        }

        if (statusChartContainer) {
            statusChartContainer.innerHTML = `
          <div class="text-center py-8 text-gray-500">
            <i class="fa fa-spinner fa-spin text-xl mb-2"></i>
            <p>加载中...</p>
          </div>
        `;
        }

        // 构建筛选参数
        const queryParams = new URLSearchParams({
            page: page,
            size: 10,
            ...(filterParams.name && { name: filterParams.name }),
            ...(filterParams.status && { status: filterParams.status })
        });

        // 调用后端API获取仓库数据
        fetch(`/warehouse?${queryParams}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('API响应数据:', apiResponse);
                warehouseTable.innerHTML = '';

                // 验证响应结构
                if (!apiResponse || apiResponse.code !== "200" || !apiResponse.data) {
                    throw new Error(apiResponse?.message || 'API响应失败');
                }

                // 解构数据
                const { content: warehouses, totalElements, totalPages, pageable } = apiResponse.data;
                currentPage = pageable.pageNumber; // 后端从0开始，前端从1开始

                // 保存所有仓库数据用于图表
                allWarehouses = warehouses;

                // 更新分页信息
                const displayPage = currentPage + 1;
                paginationInfo.textContent = `共 ${totalElements} 条记录，当前第 ${displayPage} 页`;
                updatePaginationControls(totalPages, displayPage);

                // 处理无数据情况
                if (warehouses.length === 0) {
                    warehouseTable.innerHTML = `
              <tr>
                <td colspan="9" class="py-4 text-center text-gray-500">没有找到符合条件的仓库数据</td>
              </tr>
            `;

                    if (capacityChartContainer) {
                        capacityChartContainer.innerHTML = `
                <div class="text-center py-8 text-gray-500">
                  <i class="fa fa-folder-open-o text-4xl mb-4"></i>
                  <p>暂无仓库数据</p>
                </div>
              `;
                    }

                    if (statusChartContainer) {
                        statusChartContainer.innerHTML = `
                <div class="text-center py-8 text-gray-500">
                  <i class="fa fa-folder-open-o text-4xl mb-4"></i>
                  <p>暂无仓库数据</p>
                </div>
              `;
                    }
                    return;
                }

                // 渲染仓库数据
                warehouses.forEach(warehouse => {
                    const row = document.createElement('tr');
                    row.className = 'border-b border-gray-100 hover:bg-gray-50';

                    // 从API数据中提取字段（含默认值处理）
                    const id = warehouse.warehouseId;
                    const name = warehouse.warehouseName || '未知名称';
                    const address = warehouse.address || '未设置';
                    const totalCapacity = warehouse.totalCapacity !== null && warehouse.totalCapacity !== undefined ? warehouse.totalCapacity : 0;
                    const usedCapacity = warehouse.usedCapacity !== null && warehouse.usedCapacity !== undefined ? warehouse.usedCapacity : 0;
                    const capacityPercentage = totalCapacity > 0 ? Math.round((usedCapacity / totalCapacity) * 100) : 0;
                    const status = warehouse.status || 'Unknown';
                    const manager = warehouse.managerId || '未指定';
                    const inventoryWarning = warehouse.inventoryWarning !== null && warehouse.inventoryWarning !== undefined ? warehouse.inventoryWarning : false;

                    // 确定状态标签样式
                    let statusClass = '';
                    let statusText = '';
                    switch (status) {
                        case 'Active':
                            statusClass = 'bg-green-100 text-green-800';
                            statusText = '活跃';
                            break;
                        case 'Inactive':
                            statusClass = 'bg-gray-100 text-gray-800';
                            statusText = '非活跃';
                            break;
                        case 'UnderMaintenance':
                            statusClass = 'bg-yellow-100 text-yellow-800';
                            statusText = '维护中';
                            break;
                        case 'Planned':
                            statusClass = 'bg-blue-100 text-blue-800';
                            statusText = '规划中';
                            break;
                        default:
                            statusClass = 'bg-gray-100 text-gray-800';
                            statusText = '未知';
                    }

                    // 确定库存预警图标
                    const warningIcon = inventoryWarning
                        ? `<i class="fa fa-exclamation-triangle text-red-500"></i>`
                        : `<i class="fa fa-check-circle text-green-500"></i>`;

                    row.innerHTML = `
              <td class="py-3 text-sm text-gray-600">${id}</td>
              <td class="py-3 text-sm text-gray-600">${name}</td>
              <td class="py-3 text-sm text-gray-600">${address}</td>
              <td class="py-3 text-sm text-gray-600">${totalCapacity}</td>
              <td class="py-3 text-sm text-gray-600">
                <div class="w-full bg-gray-200 rounded-full h-2.5">
                  <div class="bg-primary h-2.5 rounded-full" style="width: ${capacityPercentage}%"></div>
                </div>
                <div class="text-xs mt-1">${usedCapacity}/${totalCapacity} (${capacityPercentage}%)</div>
              </td>
              <td class="py-3 text-sm">
                <span class="px-2 py-1 rounded-full text-xs font-medium ${statusClass}">${statusText}</span>
              </td>
              <td class="py-3 text-sm text-gray-600">${manager}</td>
              <td class="py-3 text-sm text-gray-600">${warningIcon}</td>
              <td class="py-3 text-sm text-gray-600">
                <button data-id="${id}" class="edit-btn text-primary mr-2" data-permission="WAREHOUSE_EDIT">
                  <i class="fa fa-pencil"></i> 编辑
                </button>
                <button data-id="${id}" class="delete-btn text-danger" data-permission="WAREHOUSE_DELETE">
                  <i class="fa fa-trash"></i> 删除
                </button>
              </td>
            `;
                    warehouseTable.appendChild(row);
                });

                // 渲染ECharts图表
                renderCapacityBarChart(warehouses);
                renderStatusPieChart(warehouses);
            })
            .catch(error => {
                console.error('加载仓库数据失败:', error);
                warehouseTable.innerHTML = `
            <tr>
              <td colspan="9" class="py-4 text-center text-red-500">
                <i class="fa fa-exclamation-circle mr-2"></i> 加载仓库数据失败，请稍后重试
              </td>
            </tr>
          `;

                if (capacityChartContainer) {
                    capacityChartContainer.innerHTML = `
              <div class="text-center py-8 text-red-500">
                <i class="fa fa-exclamation-triangle text-4xl mb-4"></i>
                <p>加载仓库图表失败</p>
              </div>
            `;
                }

                if (statusChartContainer) {
                    statusChartContainer.innerHTML = `
              <div class="text-center py-8 text-red-500">
                <i class="fa fa-exclamation-triangle text-4xl mb-4"></i>
                <p>加载仓库图表失败</p>
              </div>
            `;
                }

                Toastify({
                    text: `加载仓库数据失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
        // 确保重新应用角色权限
        setTimeout(() => {
            applyRolePermissions();
        }, 100); // 等待数据加载完成
    };

    /**
     * 更新分页控件
     */
    const updatePaginationControls = (totalPages, currentPage) => {
        const controls = document.getElementById('paginationControls');
        controls.innerHTML = '';

        // 上一页按钮
        const prevBtn = document.createElement('button');
        prevBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === 1 ? 'opacity-50 cursor-not-allowed' : ''}`;
        prevBtn.disabled = currentPage === 1;
        prevBtn.innerHTML = '<i class="fa fa-chevron-left"></i>';
        prevBtn.addEventListener('click', () => {
            if (currentPage > 1) {
                loadWarehouses(currentPage - 2); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(prevBtn);

        // 页码按钮 (显示当前页及前后两页)
        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const pageBtn = document.createElement('button');
            pageBtn.className = `px-3 py-1 border rounded-md text-gray-700 hover:bg-gray-50 ${i === currentPage ? 'border-primary bg-primary text-white' : ''}`;
            pageBtn.textContent = i;
            pageBtn.addEventListener('click', () => {
                loadWarehouses(i - 1); // 转换为后端页码（前端页码-1）
            });
            controls.appendChild(pageBtn);
        }

        // 下一页按钮
        const nextBtn = document.createElement('button');
        nextBtn.className = `px-3 py-1 border border-gray-300 rounded-md text-gray-500 hover:bg-gray-50 ${currentPage === totalPages ? 'opacity-50 cursor-not-allowed' : ''}`;
        nextBtn.disabled = currentPage === totalPages;
        nextBtn.innerHTML = '<i class="fa fa-chevron-right"></i>';
        nextBtn.addEventListener('click', () => {
            if (currentPage < totalPages) {
                loadWarehouses(currentPage); // 转换为后端页码（前端页码-1）
            }
        });
        controls.appendChild(nextBtn);
    };

    /**
     * 渲染仓库容量使用情况柱状图
     */
    const renderCapacityBarChart = (warehouses) => {
        const chartContainer = document.getElementById('capacityBarChart');
        if (!chartContainer) return;

        // 隐藏加载状态，创建图表容器
        chartContainer.innerHTML = `
        <div class="echart-container" id="capacityEChart"></div>
      `;

        // 处理无数据情况
        if (!warehouses || warehouses.length === 0) {
            chartContainer.innerHTML = `
          <div class="text-center py-8 text-gray-500">
            <i class="fa fa-folder-open-o text-4xl mb-4"></i>
            <p>暂无仓库数据</p>
          </div>
        `;
            return;
        }

        // 准备图表数据
        const chartData = prepareCapacityChartData(warehouses);

        // 销毁已存在的图表实例（如果有）
        if (capacityChart) {
            capacityChart.dispose();
        }

        // 创建ECharts实例
        capacityChart = echarts.init(document.getElementById('capacityEChart'));

        // 配置项 - 柱状图
        const option = {
            title: {
                text: '仓库容量使用情况',
                left: 'center',
                textStyle: {
                    color: '#333'
                }
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                },
                formatter: function(params) {
                    const param = params[0];
                    return `${param.name}<br/>
                    总容量: ${param.data.total}<br/>
                    已使用: ${param.data.used}<br/>
                    使用率: ${param.data.percentage}%`;
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: chartData.names,
                axisTick: {
                    alignWithLabel: true
                },
                axisLabel: {
                    rotate: 45,
                    interval: 0
                }
            },
            yAxis: {
                type: 'value'
            },
            series: [{
                name: '容量使用',
                type: 'bar',
                data: chartData.values,
                itemStyle: {
                    color: function(params) {
                        const value = params.data.percentage;
                        if (value >= 90) return '#F53F3F'; // 红色 - 高使用率
                        if (value >= 70) return '#FF7D00'; // 橙色 - 中高使用率
                        return '#00B42A'; // 绿色 - 低使用率
                    }
                },
                label: {
                    show: true,
                    position: 'top',
                    formatter: function(params) {
                        return `${params.data.percentage}%`;
                    }
                }
            }]
        };

        // 渲染图表
        capacityChart.setOption(option);

        // 窗口大小改变时重绘图表
        window.addEventListener('resize', () => {
            if (capacityChart) {
                capacityChart.resize();
            }
        });
    };

    /**
     * 准备容量图表数据
     */
    const prepareCapacityChartData = (warehouses) => {
        const names = [];
        const values = [];

        warehouses.forEach(warehouse => {
            const name = warehouse.warehouseName || `仓库${warehouse.warehouseId}`;
            const total = warehouse.totalCapacity !== null && warehouse.totalCapacity !== undefined ? warehouse.totalCapacity : 0;
            const used = warehouse.usedCapacity !== null && warehouse.usedCapacity !== undefined ? warehouse.usedCapacity : 0;
            const percentage = total > 0 ? Math.round((used / total) * 100) : 0;

            names.push(name);
            values.push({
                value: percentage,
                total: total,
                used: used,
                percentage: percentage
            });
        });

        return {
            names,
            values
        };
    };

    /**
     * 渲染仓库状态分布饼图
     */
    const renderStatusPieChart = (warehouses) => {
        const chartContainer = document.getElementById('statusPieChart');
        if (!chartContainer) return;

        // 隐藏加载状态，创建图表容器
        chartContainer.innerHTML = `
        <div class="echart-container" id="statusEChart"></div>
      `;

        // 处理无数据情况
        if (!warehouses || warehouses.length === 0) {
            chartContainer.innerHTML = `
          <div class="text-center py-8 text-gray-500">
            <i class="fa fa-folder-open-o text-4xl mb-4"></i>
            <p>暂无仓库数据</p>
          </div>
        `;
            return;
        }

        // 准备图表数据
        const chartData = prepareStatusChartData(warehouses);

        // 销毁已存在的图表实例（如果有）
        if (statusChart) {
            statusChart.dispose();
        }

        // 创建ECharts实例
        statusChart = echarts.init(document.getElementById('statusEChart'));

        // 配置项 - 饼图
        const option = {
            title: {
                text: '仓库状态分布',
                left: 'center',
                textStyle: {
                    color: '#333'
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} (${d}%)'
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'middle',
                data: chartData.labels,
                itemWidth: 10,
                itemHeight: 10,
                textStyle: {
                    color: '#666',
                    fontSize: 12
                }
            },
            series: [{
                name: '仓库数量',
                type: 'pie',
                radius: ['40%', '75%'],
                center: ['50%', '50%'],
                data: chartData.data,
                itemStyle: {
                    borderRadius: 8,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    formatter: '{b}: {c} ({d}%)'
                },
                labelLine: {
                    show: true
                }
            }]
        };

        // 渲染图表
        statusChart.setOption(option);

        // 窗口大小改变时重绘图表
        window.addEventListener('resize', () => {
            if (statusChart) {
                statusChart.resize();
            }
        });
    };

    /**
     * 准备状态图表数据
     */
    const prepareStatusChartData = (warehouses) => {
        // 统计每种状态的仓库数量
        const statusMap = {
            'Active': 0,
            'Inactive': 0,
            'UnderMaintenance': 0,
            'Planned': 0,
            'Unknown': 0
        };

        warehouses.forEach(warehouse => {
            const status = warehouse.status || 'Unknown';
            if (statusMap.hasOwnProperty(status)) {
                statusMap[status]++;
            } else {
                statusMap['Unknown']++;
            }
        });

        // 转换为ECharts需要的数据格式
        const data = [];
        const labels = [];
        const statusTextMap = {
            'Active': '活跃',
            'Inactive': '非活跃',
            'UnderMaintenance': '维护中',
            'Planned': '规划中',
            'Unknown': '未知'
        };

        for (const [status, count] of Object.entries(statusMap)) {
            if (count > 0) {
                labels.push(statusTextMap[status]);
                data.push({
                    value: count,
                    name: statusTextMap[status]
                });
            }
        }

        return {
            data,
            labels
        };
    };

    /**
     * 显示添加仓库表单
     */
    const showAddWarehouseForm = () => {
        const modal = document.getElementById('warehouseModal');
        modal.classList.remove('hidden');

        const formContainer = document.createElement('div');
        formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
        formContainer.innerHTML = `
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-semibold text-gray-800">添加新仓库</h3>
          <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('warehouseModal').classList.add('hidden')">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <form id="addWarehouseForm" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="warehouseName">仓库名称</label>
            <input type="text" id="warehouseName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required placeholder="输入仓库名称">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="warehouseAddress">仓库地址</label>
            <input type="text" id="warehouseAddress" name="address" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required placeholder="输入仓库地址">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="warehouseCapacity">总容量</label>
            <input type="number" id="warehouseCapacity" name="capacity" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required placeholder="输入仓库总容量">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="warehouseManager">负责人</label>
            <input type="text" id="warehouseManager" name="manager" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入负责人姓名">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="warehouseStatus">仓库状态</label>
            <select id="warehouseStatus" name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
              <option value="Active">活跃</option>
              <option value="Inactive">非活跃</option>
              <option value="UnderMaintenance">维护中</option>
              <option value="Planned">规划中</option>
            </select>
          </div>
          <div class="flex items-center">
            <input type="checkbox" id="warehouseInventoryWarning" name="inventoryWarning" class="w-4 h-4 text-primary focus:ring-primary border-gray-300 rounded">
            <label for="warehouseInventoryWarning" class="ml-2 text-sm text-gray-700">启用库存预警</label>
          </div>
          <div class="flex justify-end space-x-3 mt-6">
            <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('warehouseModal').classList.add('hidden')">取消</button>
            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">添加仓库</button>
          </div>
        </form>
      `;

        modal.innerHTML = '';
        modal.appendChild(formContainer);

        // 表单提交事件
        document.getElementById('addWarehouseForm').addEventListener('submit', (e) => {
            e.preventDefault();
            addWarehouse();
        });
    };

    /**
     * 添加仓库到系统
     */
    const addWarehouse = () => {
        // 获取表单数据
        const formData = {
            warehouseName: document.getElementById('warehouseName').value,
            address: document.getElementById('warehouseAddress').value,
            totalCapacity: parseInt(document.getElementById('warehouseCapacity').value, 10),
            managerId: document.getElementById('warehouseManager').value,
            status: document.getElementById('warehouseStatus').value,
            inventoryWarning: document.getElementById('warehouseInventoryWarning').checked
        };

        // 验证表单
        if (!formData.warehouseName) {
            Toastify({
                text: "请输入仓库名称",
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            return;
        }

        if (!formData.address) {
            Toastify({
                text: "请输入仓库地址",
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            return;
        }

        if (isNaN(formData.totalCapacity) || formData.totalCapacity <= 0) {
            Toastify({
                text: "请输入有效的总容量",
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            return;
        }

        // 显示加载状态
        const submitButton = document.querySelector('#addWarehouseForm button[type="submit"]');
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 提交中...';

        // 调用API
        fetch('/warehouse', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('添加仓库API响应:', apiResponse);

                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '添加仓库';

                // 处理响应
                if (apiResponse) {
                    Toastify({
                        text: "仓库添加成功",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();
                    // 关闭表单
                    document.getElementById('warehouseModal').classList.add('hidden');
                    // 刷新仓库列表
                    loadWarehouses();
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '添加失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();
                }
            })
            .catch(error => {
                console.error('添加仓库失败:', error);
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '添加仓库';
                // 显示错误信息
                Toastify({
                    text: `添加仓库失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };

    /**
     * 加载指定仓库详情
     */
    const fetchWarehouseDetails = async (warehouseId) => {
        try {
            const response = await fetch(`/warehouse/${warehouseId}`);
            if (!response.ok) {
                throw new Error(`获取仓库详情失败: 状态码 ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('获取仓库详情失败:', error);
            Toastify({
                text: `获取仓库详情失败: ${error.message}`,
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            throw error;
        }
    };

    /**
     * 显示编辑仓库表单
     */
    const showEditWarehouseForm = (warehouseId) => {
        currentEditingWarehouseId = warehouseId;
        const modal = document.getElementById('editWarehouseModal');
        modal.classList.remove('hidden');

        const formContainer = document.createElement('div');
        formContainer.className = 'bg-white rounded-lg shadow-xl w-full max-w-md p-6';
        formContainer.innerHTML = `
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-semibold text-gray-800">编辑仓库</h3>
          <button class="text-gray-500 hover:text-gray-700" onclick="document.getElementById('editWarehouseModal').classList.add('hidden')">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="animate-pulse mb-4">
          <div class="h-6 bg-gray-200 rounded w-full mb-2"></div>
          <div class="h-6 bg-gray-200 rounded w-3/4"></div>
        </div>
        <form id="editWarehouseForm" class="space-y-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="editWarehouseName">仓库名称</label>
            <input type="text" id="editWarehouseName" name="name" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required placeholder="输入仓库名称">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="editWarehouseAddress">仓库地址</label>
            <input type="text" id="editWarehouseAddress" name="address" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required placeholder="输入仓库地址">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="editWarehouseCapacity">总容量</label>
            <input type="number" id="editWarehouseCapacity" name="capacity" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required placeholder="输入仓库总容量">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="editWarehouseManager">负责人</label>
            <input type="text" id="editWarehouseManager" name="manager" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="输入负责人姓名">
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1" for="editWarehouseStatus">仓库状态</label>
            <select id="editWarehouseStatus" name="status" class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" required>
              <option value="Active">活跃</option>
              <option value="Inactive">非活跃</option>
              <option value="UnderMaintenance">维护中</option>
              <option value="Planned">规划中</option>
            </select>
          </div>
          <div class="flex items-center">
            <input type="checkbox" id="editWarehouseInventoryWarning" name="inventoryWarning" class="w-4 h-4 text-primary focus:ring-primary border-gray-300 rounded">
            <label for="editWarehouseInventoryWarning" class="ml-2 text-sm text-gray-700">启用库存预警</label>
          </div>
          <div class="flex justify-end space-x-3 mt-6">
            <button type="button" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50" onclick="document.getElementById('editWarehouseModal').classList.add('hidden')">取消</button>
            <button type="submit" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90">保存修改</button>
          </div>
        </form>
      `;

        modal.innerHTML = '';
        modal.appendChild(formContainer);

        // 加载仓库详情
        fetchWarehouseDetails(warehouseId)
            .then(apiResponse => {
                if (apiResponse && apiResponse.code === "200" && apiResponse.data) {
                    const warehouse = apiResponse.data;
                    document.getElementById('editWarehouseName').value = warehouse.warehouseName || '';
                    document.getElementById('editWarehouseAddress').value = warehouse.address || '';
                    document.getElementById('editWarehouseCapacity').value = warehouse.totalCapacity || '';
                    document.getElementById('editWarehouseManager').value = warehouse.managerId || '';
                    document.getElementById('editWarehouseStatus').value = warehouse.status || 'Active';
                    document.getElementById('editWarehouseInventoryWarning').checked = warehouse.inventoryWarning || false;

                    // 移除加载动画
                    const loadingPlaceholder = modal.querySelector('.animate-pulse');
                    if (loadingPlaceholder) {
                        loadingPlaceholder.remove();
                    }
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '获取仓库详情失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();

                    // 关闭模态框
                    setTimeout(() => {
                        modal.classList.add('hidden');
                    }, 1500);
                }
            })
            .catch(error => {
                // 关闭模态框
                modal.classList.add('hidden');
            });

        // 表单提交事件
        document.getElementById('editWarehouseForm').addEventListener('submit', (e) => {
            e.preventDefault();
            updateWarehouse();
        });
    };

    /**
     * 编辑仓库
     */
    const editWarehouse = (warehouseId) => {
        showEditWarehouseForm(warehouseId);
    };

    /**
     * 更新仓库信息
     */
    const updateWarehouse = () => {
        if (!currentEditingWarehouseId) {
            Toastify({
                text: "未选择要编辑的仓库",
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            return;
        }

        // 获取表单数据
        const formData = {
            warehouseName: document.getElementById('editWarehouseName').value,
            address: document.getElementById('editWarehouseAddress').value,
            totalCapacity: parseInt(document.getElementById('editWarehouseCapacity').value, 10),
            managerId: document.getElementById('editWarehouseManager').value,
            status: document.getElementById('editWarehouseStatus').value,
            inventoryWarning: document.getElementById('editWarehouseInventoryWarning').checked
        };

        // 验证表单
        if (!formData.warehouseName) {
            Toastify({
                text: "请输入仓库名称",
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            return;
        }

        if (!formData.address) {
            Toastify({
                text: "请输入仓库地址",
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            return;
        }

        if (isNaN(formData.totalCapacity) || formData.totalCapacity <= 0) {
            Toastify({
                text: "请输入有效的总容量",
                duration: 3000,
                gravity: "top",
                position: "right",
                backgroundColor: "#f44336",
            }).showToast();
            return;
        }

        // 显示加载状态
        const submitButton = document.querySelector('#editWarehouseForm button[type="submit"]');
        submitButton.disabled = true;
        submitButton.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';

        // 调用API
        fetch(`/warehouse/${currentEditingWarehouseId}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(formData),
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(apiResponse => {
                console.log('更新仓库API响应:', apiResponse);

                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '保存修改';

                // 处理响应
                if (apiResponse) {
                    Toastify({
                        text: "仓库更新成功",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();
                    // 关闭表单
                    document.getElementById('editWarehouseModal').classList.add('hidden');
                    // 刷新仓库列表
                    loadWarehouses();
                } else {
                    const errorMsg = apiResponse && apiResponse.message
                        ? apiResponse.message
                        : '更新失败：未知错误';
                    Toastify({
                        text: errorMsg,
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#f44336",
                    }).showToast();
                }
            })
            .catch(error => {
                console.error('更新仓库失败:', error);
                // 恢复按钮状态
                submitButton.disabled = false;
                submitButton.innerHTML = '保存修改';
                // 显示错误信息
                Toastify({
                    text: `更新仓库失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };

    /**
     * 删除仓库
     */
    const deleteWarehouse = (warehouseId) => {
        // 确认对话框
        if (!confirm("确定要删除此仓库吗？删除后将无法恢复，且相关库存数据也将受影响。")) {
            return;
        }

        // 显示加载状态
        const deleteButtons = document.querySelectorAll(`button[onclick="deleteWarehouse(${warehouseId})"]`);
        deleteButtons.forEach(btn => {
            btn.disabled = true;
            btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 删除中...';
        });

        // 调用API
        fetch(`/warehouse/${warehouseId}`, {
            method: 'DELETE',
        })
            .then(response => {
                if (response.ok) {
                    Toastify({
                        text: "仓库删除成功",
                        duration: 3000,
                        gravity: "top",
                        position: "right",
                        backgroundColor: "#4CAF50",
                    }).showToast();
                    // 刷新列表
                    loadWarehouses();
                } else {
                    throw new Error(`删除失败: ${response.statusText}`);
                }
            })
            .then(apiResponse => {
                console.log('删除仓库API响应:', apiResponse);
                // 恢复按钮状态
                deleteButtons.forEach(btn => {
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fa fa-trash"></i> 删除';
                });
            })
            .catch(error => {
                console.error('删除仓库失败:', error);
                // 恢复按钮状态
                deleteButtons.forEach(btn => {
                    btn.disabled = false;
                    btn.innerHTML = '<i class="fa fa-trash"></i> 删除';
                });
                // 显示错误信息
                Toastify({
                    text: `删除仓库失败: ${error.message}`,
                    duration: 3000,
                    gravity: "top",
                    position: "right",
                    backgroundColor: "#f44336",
                }).showToast();
            });
    };

    /**
     * 初始化侧边栏导航
     */
    const initSidebarNavigation = () => {
        const sidebarItems = document.querySelectorAll('.sidebar-item');

        sidebarItems.forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();

                const path = item.getAttribute('data-path');
                if (!path) return;

                // 更新激活状态
                updateActiveItem(item);

                // 显示加载指示器
                showPageLoader();

                // 使用平滑过渡加载新页面
                setTimeout(() => {
                    window.location.href = path;
                }, 300); // 动画持续时间
            });
        });
    };

    /**
     * 更新激活菜单项
     */
    const updateActiveItem = (activeItem) => {
        document.querySelectorAll('.sidebar-item').forEach(item => {
            item.classList.remove('active');
        });
        activeItem.classList.add('active');
    };

    /**
     * 设置当前页面菜单项为激活状态
     */
    const setCurrentPageActive = () => {
        const currentPath = window.location.pathname;
        const sidebarItems = document.querySelectorAll('.sidebar-item');

        sidebarItems.forEach(item => {
            const itemPath = item.getAttribute('data-path');
            if (itemPath && currentPath.endsWith(itemPath)) {
                updateActiveItem(item);
                return;
            }
        });
    };

    /**
     * 显示页面加载指示器
     */
    const showPageLoader = () => {
        const mainContent = document.querySelector('main');

        // 创建加载指示器元素
        const loader = document.createElement('div');
        loader.className = 'fixed inset-0 bg-white bg-opacity-80 flex items-center justify-center z-50 transition-opacity duration-300';
        loader.innerHTML = `
        <div class="text-center">
          <div class="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
          <p class="mt-4 text-gray-600">加载中...</p>
        </div>
      `;

        // 添加到页面
        document.body.appendChild(loader);

        // 300ms后移除（与导航延迟匹配）
        setTimeout(() => {
            loader.classList.add('opacity-0');
            setTimeout(() => {
                document.body.removeChild(loader);
            }, 300);
        }, 300);
    };

    /**
     * 页面卸载时销毁图表实例，释放资源
     */
    window.addEventListener('beforeunload', () => {
        if (capacityChart) {
            capacityChart.dispose();
            capacityChart = null;
        }
        if (statusChart) {
            statusChart.dispose();
            statusChart = null;
        }
    });
</script>
</body>

</html>